﻿using DotNetCore.CAP;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Polly;
using SkiaSharp; 
using SSPivot.Data.MultiTenancy;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; 

namespace SSPivot.AspNetCore.Repository
{
    public sealed class UnitOfWork : IUnitOfWork
    {

        private readonly AppDbContext<DbContext> _context;
        private readonly ICapPublisher _capPublisher;
        private IDbContextTransaction _transaction;

        public UnitOfWork(AppDbContext<DbContext> context, ICapPublisher capPublisher)
        {
            _context = context;
            _capPublisher = capPublisher;
        }

        public ICapTransaction BeginTransaction()
        {
            _transaction = _context.Database.BeginTransaction(_capPublisher, autoCommit: false);
            return _transaction as ICapTransaction;
        }

        public async Task<bool> CommitAsync()
        {
            try
            {
                await _context.SaveChangesAsync();
                if (_transaction != null)
                {
                    await _transaction.CommitAsync();
                }
                return true;
            }
            catch
            {
                Rollback();
                throw;
            }
        }

        private void Rollback()
        {
            _transaction?.Rollback();
            _transaction?.Dispose();
        }

        public void Dispose()
        {
            _transaction?.Dispose();
            _context.Dispose();
        }
    }

}
